package com.dhcc.sds.custom.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.core.framework.base.controller.BaseController;
import com.dhcc.core.framework.base.warpper.EmptyWarpper;
import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.exception.BizExceptionEnum;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.result.node.ZTreeNode;
import com.dhcc.core.framework.result.page.PageFactory;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.sds.base.entity.SdsIndexFieldEntity;
import com.dhcc.sds.base.entity.SdsIndexHeaderEntity;
import com.dhcc.sds.base.entity.SdsQcentityEntity;
import com.dhcc.sds.base.service.*;
import com.dhcc.sds.custom.entity.SdsCusIndexFieldEntity;
import com.dhcc.sds.custom.entity.SdsCusIndexHeaderEntity;
import com.dhcc.sds.custom.service.ISdsCusIndexFieldService;
import com.dhcc.sds.custom.service.ISdsCusIndexHeaderService;
import com.dhcc.sds.custom.warpper.SdsCusIndexHeaderWarpper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 自定义病种指标统计配置
 *
 * @ClassName: SdsCusIndexHeaderController
 * @Description: TODO
 * @author yhw
 * @date 2024-07-01 10:09:57
 */
@Controller
@RequestMapping("${sys.backendPath}/sds/sdscusindexheader")
public class SdsCusIndexHeaderController extends BaseController {

    private String PREFIX = "/backend/sds/sdscusindexheader/";

    @Autowired
    private ISdsIndexHeaderService sdsIndexHeaderService;

    @Autowired
    private ISdsQcformItemService sdsQcformItemService;

    @Autowired
    private ISdsCommonService sdsCommonService;

    @Autowired
    private ISdsCusIndexFieldService sdsCusIndexFieldService;

    @Autowired
    private ISdsIndexFieldService sdsIndexFieldService;

    @Autowired
    private ISdsQcentityService sdsQcentityService;

    @Autowired
    private ISdsCusIndexHeaderService sdsCusIndexHeaderService;

    /**
     * 跳转到指标统计配置列表首页
     */
    @RequestMapping("")
    public String index() {
        return sdsCusIndexHeaderService.index();
    }

    /**
     * 跳转到新增指标
     */
    @RequestMapping("/to_add/{entityId}/{indexType}")
    public String toAdd(@PathVariable Long entityId, @PathVariable Integer indexType, Model model) {
        return sdsCusIndexHeaderService.toAdd(entityId,indexType,model);
    }

    /**
     * 获取指标列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam Map<String, Object> params) {
        List<Map<String, Object>> indexHeader = sdsCusIndexHeaderService.selectIndexHeader(params);
        return super.warpObject(new SdsCusIndexHeaderWarpper(indexHeader));
    }

    /**
     * 新增指标
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(SdsCusIndexHeaderEntity sdsCusIndexHeaderEntity) {
        if (CommonUtil.isOneEmpty(sdsCusIndexHeaderEntity)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        sdsCusIndexHeaderEntity.init();
        sdsCusIndexHeaderEntity.insert();
        return R.ok();
    }

    /**
     * 修改指标
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(SdsCusIndexHeaderEntity sdscusIndexHeaderEntity) {
        if (CommonUtil.isOneEmpty(sdscusIndexHeaderEntity)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        SdsCusIndexHeaderEntity old = this.sdsCusIndexHeaderService.selectById(sdscusIndexHeaderEntity.getId());

        old.setTitle(sdscusIndexHeaderEntity.getTitle());
        old.setIndexType(sdscusIndexHeaderEntity.getIndexType());
        old.setParentId(sdscusIndexHeaderEntity.getParentId());
        old.setField(sdscusIndexHeaderEntity.getField());
        old.setBtIsActive(sdscusIndexHeaderEntity.getBtIsActive());
        old.setAnalysisStatus(sdscusIndexHeaderEntity.getAnalysisStatus());
        old.setSort(sdscusIndexHeaderEntity.getSort());
        old.setHeaderType(sdscusIndexHeaderEntity.getHeaderType());
        old.setBtResume(sdscusIndexHeaderEntity.getBtResume());
        old.setIsImportant(sdscusIndexHeaderEntity.getIsImportant());
        old.init();
        old.updateAllColumnById();
        return R.ok();
    }

    /**
     * 获取指标列表
     */
    @RequestMapping(value = "/tree/{entityId}/{indexType}")
    @ResponseBody
    public List<ZTreeNode> tree(@PathVariable Long entityId, @PathVariable Integer indexType) {
        return sdsCusIndexHeaderService.getIndexHeaderTree(entityId, indexType);
    }


    /**
     * 获取病种项目列表
     */
    @RequestMapping(value = "/itemTree")
    @ResponseBody
    public List<ZTreeNode> itemTree() {
        return sdsQcformItemService.getItemTree(1l);
    }

    /**
     * 跳转到指标详情列表页面
     */
    @RequestMapping(value = "/to_update/{cusIndexHeaderId}")
    public String toUpdate(@PathVariable Long cusIndexHeaderId, Model model) {
        return sdsCusIndexHeaderService.toUpdate(cusIndexHeaderId,model);
    }

    /**
     * 删除指标
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Long cusIndexHeaderId) {
        sdsCusIndexFieldService.deleteByIndexHeaderId(cusIndexHeaderId);
        sdsCusIndexHeaderService.deleteById(cusIndexHeaderId);
        return R.ok();
    }

    /**
     * 跳转到指标对照病种项目页面
     */
    @RequestMapping(value = "/to_compare/{cusIndexHeaderId}")
    public String toCompare(@PathVariable Long cusIndexHeaderId, Model model) {
        return sdsCusIndexHeaderService.toCompare(cusIndexHeaderId,model);
    }

    /**
     * 新增指标对照项目
     */
    @RequestMapping(value = "/addItem")
    @ResponseBody
    public Object addItem(SdsCusIndexFieldEntity sdsCusIndexFieldEntity) {
        if (CommonUtil.isOneEmpty(sdsCusIndexFieldEntity)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        Long datasource = sdsCusIndexFieldEntity.getDatasource();
        if (ObjectUtils.isEmpty(datasource)){
            return R.ok();
        }
        sdsCusIndexFieldEntity.insert();
        return R.ok();
    }

    /**
     * 修改指标对照项目
     */
    @RequestMapping(value = "/updateItem")
    @ResponseBody
    public Object updateItem(SdsCusIndexFieldEntity sdsCusIndexFieldEntity) {
        if (CommonUtil.isOneEmpty(sdsCusIndexFieldEntity)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        SdsCusIndexFieldEntity old = sdsCusIndexFieldService.selectById(sdsCusIndexFieldEntity.getId());

        old.setEntityId(sdsCusIndexFieldEntity.getEntityId());
        old.setIndexHeaderId(sdsCusIndexFieldEntity.getIndexHeaderId());
        old.setDatasource(sdsCusIndexFieldEntity.getDatasource());
        old.setDic(sdsCusIndexFieldEntity.getDic());
        old.setValueTime(sdsCusIndexFieldEntity.getValueTime());
        old.setItemType(sdsCusIndexFieldEntity.getItemType());
        old.updateAllColumnById();
        return R.ok();
    }

    /**
     * 删除指标对照项目
     */
    @RequestMapping(value = "/deleteItem")
    @ResponseBody
    public Object deleteItem(@RequestParam Long sdscusIndexFieldId) {
        this.sdsCusIndexFieldService.deleteById(sdscusIndexFieldId);
        return R.ok();
    }

    /**
     * 获取指标对照项目列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/listItem/{cusIndexHeaderId}/{itemType}")
    @ResponseBody
    public Object listItem(@RequestParam Map<String, Object> params, @PathVariable Long cusIndexHeaderId, @PathVariable Long itemType) {
        params.put("indexHeaderId", cusIndexHeaderId);
        params.put("itemType", itemType);
        Page<SdsCusIndexFieldEntity> page = new PageFactory<SdsCusIndexFieldEntity>().dataGridPage();
        List<SdsCusIndexFieldEntity> result = this.sdsCusIndexFieldService.page(page,params);
        page.setRecords((List<SdsCusIndexFieldEntity>) new EmptyWarpper(result).warp());
        return R.packForBT(page);
    }

    /**
     * 修改表达式
     */
    @RequestMapping(value = "/updateExpress")
    @ResponseBody
    public Object updateExpress(@RequestParam Map<String, Object> params) {
        if (CommonUtil.isOneEmpty(params.get("cusIndexHeaderId"))) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        SdsCusIndexHeaderEntity sdsCusIndexHeaderEntity = new SdsCusIndexHeaderEntity();
        sdsCusIndexHeaderEntity.setId(Long.valueOf(params.get("cusIndexHeaderId").toString()));
        try {
            if (CommonUtil.isNotEmpty(params.get("express"))) {
                sdsCusIndexHeaderEntity.setExpress(URLDecoder.decode(params.get("express").toString(), "UTF-8"));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        this.sdsCusIndexHeaderService.updateById(sdsCusIndexHeaderEntity);
        return R.ok();
    }

    @RequestMapping("/export")
    public void export(@RequestParam(required = false) String entityId,
                       HttpServletRequest request,
                       HttpServletResponse response) {

        // 获取病种信息
        SdsQcentityEntity qcEntity = this.sdsQcentityService.selectById(entityId);
        // 查询指标配置
        Map params = new HashMap();
        params.put("qcEntity", entityId);
        List<SdsIndexHeaderEntity> res = new ArrayList<>();
        //查询一级节点
        List<SdsIndexHeaderEntity> parIndexHeaderEntities = this.sdsIndexHeaderService.getParentIndexHeader(params);
        //查询二级节点
        for (SdsIndexHeaderEntity sdsIndexHeaderEntity : parIndexHeaderEntities){
            res.add(sdsIndexHeaderEntity);
            params.put("parentId", sdsIndexHeaderEntity.getId());
            List<SdsIndexHeaderEntity> sonIndexHeaderEntities = sdsCusIndexHeaderService.list(params);
           for (SdsIndexHeaderEntity sdsIndexHeaderEntity1 : sonIndexHeaderEntities){
               res.add(sdsIndexHeaderEntity1);
           }
        }
        // 查询项目对照
        List<SdsIndexFieldEntity> sdsIndexFieldEntityList = new ArrayList<>();
        // 通过工具类创建writer，默认创建xls格式
        BigExcelWriter writer = (BigExcelWriter) ExcelUtil.getBigWriter();
        // 重命名第一个Sheet的名称，不然会默认多出一个Sheet1的页
        writer.renameSheet("指标");
        // 一次性写出内容，使用默认样式
        if (CommonUtil.isNotEmpty(res)) {
            ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();
            int i = 0;
            for (SdsIndexHeaderEntity obj : res) {
                Map<String, Object> row = new LinkedHashMap<>();
                String indexType = obj.getIndexType().toString();
                if (Objects.equals("1", indexType)){
                    indexType = "合计指标";
                }else {
                    indexType = "明细指标";
                }
                String headerType = obj.getHeaderType().toString();
                if (Objects.equals("1", headerType)){
                    headerType = "父指标";
                }else {
                    headerType = "子指标";
                }
                SdsIndexHeaderEntity pIndexHeader = this.sdsIndexHeaderService.selectById(obj.getParentId());
                String parentName = "";
                if (!StringUtils.isEmpty(pIndexHeader)){
                    parentName = pIndexHeader.getTitle();
                }

                row.put("病种", qcEntity.getAbbrev());
                row.put("统计类型", indexType);
                row.put("指标类型", headerType);
                row.put("指标名称", obj.getTitle());
                row.put("指标字段", obj.getField());
                row.put("父级编号", parentName);
                row.put("表达式", obj.getExpress());
                row.put("备注", obj.getBtResume());
                row.put("排序", obj.getSort());
                row.put("是否有效", obj.getBtIsActive()!=0?"是":"否");
                row.put("重点指标", obj.getIsImportant()!=0?"是":"否");
                rows.add(row);

                // 查询项目对照
                params.put("indexHeaderId", obj.getId());
                List<SdsIndexFieldEntity> sdsIndexFieldEntityList1 = this.sdsIndexFieldService.list(params);
                if (sdsIndexFieldEntityList1.size()>0) {
                    sdsIndexFieldEntityList.addAll(sdsIndexFieldEntityList1);
                }

            }
            writer.write(rows);
            writer.setColumnWidth(0, 20);
            writer.setColumnWidth(1, 20);
            writer.setColumnWidth(2, 20);
            writer.setColumnWidth(3, 30);
            writer.setColumnWidth(4, 20);
            writer.setColumnWidth(5, 30);
            writer.setColumnWidth(6, 20);
            writer.setColumnWidth(7, 30);
            writer.setColumnWidth(8, 10);
            writer.setColumnWidth(9, 10);
        } else {
            List<String> row = CollUtil.newArrayList("无数据");
            List<List<String>> rows = new ArrayList<List<String>>();
            rows.add(row);
            writer.write(rows);
        }

        writer.setSheet("项目对照");
        if (CommonUtil.isNotEmpty(sdsIndexFieldEntityList)) {
            ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();
            for (SdsIndexFieldEntity obj : sdsIndexFieldEntityList) {
                Map<String, Object> row = new LinkedHashMap<>();
                row.put("病种", qcEntity.getAbbrev());
                SdsIndexHeaderEntity sdsIndexHeaderEntity = this.sdsIndexHeaderService.selectById(obj.getIndexHeaderId());
                String indexType = sdsIndexHeaderEntity.getIndexType().toString();
                if (Objects.equals("1", indexType)){
                    indexType = "合计指标";
                }else {
                    indexType = "明细指标";
                }
                row.put("统计类型", indexType);
                row.put("指标名称", sdsIndexHeaderEntity.getTitle());
                row.put("项目代码", obj.getItemCode());
                row.put("项目", sdsQcformItemService.selectById(obj.getItemId()).getBtCode());
                rows.add(row);
            }
            writer.write(rows);
            writer.setColumnWidth(0, 20);
            writer.setColumnWidth(1, 20);
            writer.setColumnWidth(2, 30);
            writer.setColumnWidth(3, 10);
            writer.setColumnWidth(4, 30);
        } else {
            List<String> row = CollUtil.newArrayList("无数据");
            List<List<String>> rows = new ArrayList<List<String>>();
            rows.add(row);
            writer.write(rows);
        }

        ServletOutputStream out = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = qcEntity.getAbbrev()+"_" + sdf.format(new Date()) + ".xlsx";
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO8859_1"));
            out = response.getOutputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            writer.flush(out);
            // 关闭writer，释放内存
            writer.close();
        }
    }

    /**
     * 跳转到导入病种指标的页面
     */
    @RequestMapping("/to_import")
    public String toImport() {
        return PREFIX + "import.html";
    }

    /**
     * 导入病种指标
     */
    @RequestMapping(method = RequestMethod.POST, path = "/import")
    @ResponseBody
    public R importItem(@RequestPart("file") MultipartFile file) {
        ExcelReader reader;
        try {
            reader = ExcelUtil.getReader(file.getInputStream(),"指标");
            List<List<Object>> indexAll = reader.read();
            String entityAbbrev = indexAll.get(1).get(0).toString();
            SdsQcentityEntity sdsQcentityEntity = sdsQcentityService.selectOne(new EntityWrapper<SdsQcentityEntity>()
                    .eq("abbrev", entityAbbrev)
                    .eq("is_active", 1));
            List<SdsIndexHeaderEntity> sdsIndexHeaderEntities = sdsIndexHeaderService.selectList(new EntityWrapper<SdsIndexHeaderEntity>()
                    .eq("entity_id", sdsQcentityEntity.getId()));
            if (!sdsIndexHeaderEntities.isEmpty()){
                sdsIndexHeaderService.delete(new EntityWrapper<SdsIndexHeaderEntity>()
                .eq("entity_id", sdsQcentityEntity.getId()));
            }
            this.sdsIndexHeaderService.importIndexHeader(indexAll, sdsQcentityEntity.getId());
            reader = ExcelUtil.getReader(file.getInputStream(),"项目对照");
            List<List<Object>> indexItemAll = reader.read();
            List<SdsIndexFieldEntity> sdsIndexFieldEntityList = sdsIndexFieldService.selectList(new EntityWrapper<SdsIndexFieldEntity>()
                    .eq("entity_id", sdsQcentityEntity.getId()));
            if (!sdsIndexFieldEntityList.isEmpty()){
                sdsIndexFieldService.delete(new EntityWrapper<SdsIndexFieldEntity>()
                        .eq("entity_id", sdsQcentityEntity.getId()));
            }
            this.sdsIndexHeaderService.importIndexItem(indexItemAll, sdsQcentityEntity.getId());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return R.error(e.getMessage());
        }
        return R.ok();
    }

    /**
     * 查询指标统计展示指标
     * @param params
     * @return
     */
    @RequestMapping(value = "/getAnalysisIndexHeader")
    @ResponseBody
    public Object getAnalysisIndexHeader(@RequestParam Map<String, String> params) {
        return sdsIndexHeaderService.getAnalysisCaseDic(params);
    }

    /**
     * @Description: 修改指标状态
     * @Title: changeStatus
     * @param params
     */
    @RequestMapping(value = "/changeStatus")
    @ResponseBody
    public Object changeStatus(@RequestParam Map<String, String> params) {
        SdsIndexHeaderEntity entity = new SdsIndexHeaderEntity();
        entity.setId(Long.parseLong(params.get("id")));
        entity.setAnalysisStatus(Integer.parseInt(params.get("status")));
        this.sdsIndexHeaderService.updateById(entity);
        return R.ok();
    }
}
